package com.crm.kz.common;


import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import android.provider.Settings;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.alibaba.fastjson.JSON;

public class HttpUtils {

    public HttpUtils(){

    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }
    public static DownloadManager downloadManager;
    public static String gethttpresult(String urlStr) {
        try {
            URL url = new URL(urlStr);//获取url对象
            HttpURLConnection connect = (HttpURLConnection) url.openConnection();//url对象进行http连接
            connect.setReadTimeout(6000);
            connect.setRequestMethod("POST");
            InputStream input = connect.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String line = null;
            System.out.println(connect.getResponseCode());
            StringBuffer sb = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sb.append(line);//逐行读取传来的String
            }
            return sb.toString();
        } catch (Exception e) {
            System.out.println(e.toString());
            return null;
        }
    }

    public static void postObject(String url,HttpCellBack httpCellBack) {
        Handler handler = new Handler();
        new Thread(){
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
//                RequestBody formBody = new FormBody.Builder()
//                        .add("version","xxversionxx213")
//
//                        .build();
                String json = "{\"id\":1,\"version\":\"v15\"}";
                RequestBody formBody = RequestBody.create(
                        MediaType.parse("application/json"), json);

                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8100/system/test")
                        .post(formBody)
//                        .url("http://192.168.0.103:8100/system/test")
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    System.out.println();
                    Map<String, Object> map = new HashMap<>();
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONObject jsonObject2 = (JSONObject) jsonObject.get("data");
                    Iterator<String> keys = jsonObject2.keys();
                    while(keys.hasNext()) {
                        String key = keys.next();
                        Object value = jsonObject2.get(key);
                        map.put(key, value);
                    }
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            httpCellBack.cellback(map);
                        }
                    };
                    handler.post(runnable);
//                    httpCellBack.cellback(map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

            }
        }.start();
    }
    public static JSONArray postArray(String url) throws JSONException {
        String result = HttpUtils.gethttpresult(url);//利用工具类获取网络连接
        JSONArray post_all = new JSONArray(result);//将返回的数据转换为JSON串格式
//                        JSONArray post_all = result_json.getJSONArray("post_all");
//        for (int i = 0; i < post_all.length(); i++) {
//            post post_data = new post();//实例化post对象，用于存装从JSON解析出来的数据
//            JSONObject object = post_all.getJSONObject(i);
//            post_data.post_id = Integer.parseInt(object.getString("post_id"));
//            post_data.post_context = object.getString("post_context");
//            post_data.post_star = Integer.parseInt(object.getString("post_star"));
//            post_data.post_replay = Integer.parseInt(object.getString("post_replay"));
//            post_list.add(post_data);//将一个个装好JSON数据的对象加入到对象list中
//        }

        return null;
    }

    public static void androidUpdate(Context context) {
        if(!isNetworkAvailable(context)){
            Toast.makeText(context, "当前没有网络", Toast.LENGTH_SHORT).show();
            return;
        }
        Handler handler = new Handler();

        new Thread(){
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                String json = "{\"id\":1,\"version\":\"v15\"}";
                RequestBody formBody = new FormBody.Builder()
                    .add("version","xxversionxx213")

                    .build();
                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8100/system/CheckVersion")
                        .post(formBody)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    InputStream is = response.body().byteStream();

                    FileOutputStream  out = new FileOutputStream(context.getCacheDir()+"/app-release.apk", false);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        out.write(is.readAllBytes());
                    }
                    is.close();
                    out.close();

                    File fileLocation = new File(context.getCacheDir()+"/app-release.apk");//APK名称
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", fileLocation);
                    System.out.println(context.getApplicationContext().getPackageName() + ".provider");
                    intent.setDataAndType(photoURI,"application/vnd.android.package-archive");
//                    intent.setDataAndType(Uri.fromFile(fileLocation), "application/vnd.android.package-archive");
                    context.startActivity(intent);
                    Process.killProcess(Process.myPid());//安装完之后会提示”完成” “打开”。
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                        }
                    };
                    handler.post(runnable);
//                    httpCellBack.cellback(map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }.start();
    }

}
